package com.tcsl.mylibrary;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.cpos.pay.sdk.PayClient;
import com.cpos.pay.sdk.config.AcquirerInfo;
import com.cpos.pay.sdk.config.MerchantConfig;
import com.cpos.pay.sdk.protocol.Key;
import com.cpos.pay.sdk.protocol.SaleRequest;
import com.cpos.pay.sdk.protocol.TransActionResult;

import java.util.ArrayList;


/**
 * 描述:
 * <p/>作者：wjx
 * <p/>创建时间: 2017/5/27 9:32
 */
public class PayCPos extends TcslPay {
    /**
     * 支付通道id
     */
    private int cposAcquirerId;

    public PayCPos(Context context) {
        super(context);
        init();
    }

    @Override
    protected void pay(Float money, String orderNo, String merchantNo) {
        if (cposAcquirerId == -1) {
            mListener.payError("请先启动收银台，并下载商户参数");
            return;
        }
        if (cposAcquirerId == -2) {
            mListener.notSupport();
            return;
        }
        long timeMillis = System.currentTimeMillis();
        String mTradeNo = orderNo + "_" + timeMillis;
        String amount = String.valueOf(Math.round((Double.valueOf(money) * 100)));
        SaleRequest saleRequest = new SaleRequest();
        // 2017/4/12 此处的需要4.0jar和收银台进行支持，才会支持选择一个银行卡支付方式，就能自动选择通道
        saleRequest.acquirerId = cposAcquirerId;
        saleRequest.transAmount = amount;
        saleRequest.orderNo = mTradeNo;
        try {
            PayClient.sale(mActivity, saleRequest);
        } catch (Exception e) {
            mListener.notSupport();
        }
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Key.REQUEST_CODE_SALE) {
            String resp = data.getStringExtra(Key.EXTRA_RESPONE);
            Log.e(TAG, resp);
            TransActionResult transActionResult = TransActionResult.parse(resp);
            if (transActionResult.succeeded()) {
                mListener.paySuccess("交易成功", "");
            } else {
                String errorMsg = transActionResult.getErrorMsg();
                mListener.payError(errorMsg);
            }
            return true;
        } else {
            return false;
        }
    }

    private void init() {
        cposAcquirerId = TCSLApplication.getInstance().CreateSystem().getCPOSacquirerId();
        MerchantConfig merchantConfig = null;
        try {
            merchantConfig = PayClient.registerMerchantInfoListener(mContext, new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent != null && intent.hasExtra(Key.EXTRA_MERCHANTCONFIG)) {
                        MerchantConfig config = MerchantConfig.parse(intent.getStringExtra(Key.EXTRA_MERCHANTCONFIG));
                        int acquirerId = findBankcardAcquirerId(config);
                        if (acquirerId != -1) {
                            cposAcquirerId = acquirerId;
                            TCSLApplication.getInstance().CreateSystem().setCPOSacquirerId(acquirerId);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            cposAcquirerId = -2;
        }
        int acquirerId = findBankcardAcquirerId(merchantConfig);
        if (acquirerId != -1) {
            cposAcquirerId = acquirerId;
            TCSLApplication.getInstance().CreateSystem().setCPOSacquirerId(acquirerId);
        }
    }

    /**
     * 获取银行卡对应的通道ID
     *
     * @param merchantConfig
     * @return
     */
    protected int findBankcardAcquirerId(MerchantConfig merchantConfig) {
        if (merchantConfig != null) {
            ArrayList<AcquirerInfo> acquirerInfos =
                    merchantConfig.getPaymentConfig().getAcquirers();
            for (AcquirerInfo acquirerInfo : acquirerInfos) {
                int acquirerId = acquirerInfo.getAcquirerId();
                if (acquirerInfo.getEnabled() && acquirerId <
                        AcquirerInfo.ACQUIRER_UNIONPAY_MAXID) {
                    return acquirerId;//这是本商户开通的银行卡支付通道
                }
            }
        }
        return -1;//如果没有开通，返回-1
    }
}
